﻿using System;
using System.Configuration;
using System.IO;
using System.Threading;
using DevMaker.CM.Mailing.App_code;
using log4net;


namespace DevMaker.CM.Mailing {
    class Program {
        private static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static void Main(string[] args) {

            log4net.Config.XmlConfigurator.Configure();
            Log.Info("Iniciando la aplicacion");
            logAllSettings();
            var timer = System.Diagnostics.Stopwatch.StartNew();
            Log.InfoFormat("Buscando Boletas del dia  {0}", Util.FechaHoy);
            var batchSize = 0;
            var secondByBatch = 0;


            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["batchSize"])) {
                batchSize = Convert.ToInt16(ConfigurationManager.AppSettings["batchSize"]);
                secondByBatch = Convert.ToInt16(ConfigurationManager.AppSettings["secondByBatch"]);

            }

            var timerDao = System.Diagnostics.Stopwatch.StartNew();
            var boletas = new BoletaDao().ObtieneBoletas();

            Log.InfoFormat("Se encontraron {0} boletas en {1}", boletas.Count, timerDao.Elapsed);
            timerDao.Stop();

            Log.InfoFormat("Se generaran los archivos en  {0} ", Util.PathFile);
            ValidaCreaPath();

            //Generación de PDF
            Log.Info("Comienzo generacion de boletas en PDF");
            var timerPDF = System.Diagnostics.Stopwatch.StartNew();
             foreach (var boleta in boletas)
                 GeneraPdfBoleta.Generar(boleta);
            Log.InfoFormat("Fin generacion de boletas en PDF en {0}", timerPDF.Elapsed);
            timerPDF.Stop();


            //Envio de boletas por Mail
            if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["EnabledMail"]))
                if (Convert.ToBoolean(ConfigurationManager.AppSettings["EnabledMail"])) {
                    Log.Info("Comienzo envio de correo");
                    var i = 1;
                    foreach (var boleta in boletas) {
                        //Envio por correo
                        var timerEnvio = System.Diagnostics.Stopwatch.StartNew();
                            EnviaPdfBoleta.Envia(boleta);
                        
                        Log.DebugFormat("enviado correo {0} de {1} en {2}", i, boletas.Count, timerEnvio.Elapsed);
                        if (batchSize != 0)
                            if (i % batchSize == 0) {
                                Log.DebugFormat("esperando  {0} seg...", secondByBatch);
                                Thread.Sleep(new TimeSpan(0, 0, secondByBatch));
                            }


                        i++;
                    }
                    Log.Info("fin envio de correo");
                }

            Log.Info("La aplicacion se demoro en total -->" + timer.Elapsed);
            return;
        }

        private static void ValidaCreaPath() {
            try {
                if (!Directory.Exists(Util.PathFile)) {
                    Directory.CreateDirectory(Util.PathFile);
                }
            } catch (Exception ex) {
                Log.Error(ex);
            }

        }

        private static void logAllSettings() {
            try {
                Log.Info("Los valores de configuracion son:");
                var appSettings = ConfigurationManager.AppSettings;

                if (appSettings.Count == 0) {
                    Log.Info("AppSettings is empty.");
                } else {
                    foreach (var key in appSettings.AllKeys) {
                        Log.InfoFormat("Key: {0} Value: {1}", key, appSettings[key]);
                    }
                }
            } catch (ConfigurationErrorsException ex) {
                Log.Error(ex);
            }
        }
    }
}

